<template>
  <div class="profile-page">
    <h1 class="page-title">个人中心</h1>

    <!-- 用户信息 -->
    <el-card class="user-profile" v-loading="loading">
      <div class="profile-header">
        <el-avatar :size="120" :src="defaultAvatar" class="user-avatar"></el-avatar>
        <div class="user-info">
          <h2 class="user-name">{{ user.userName }}</h2>
          <div class="user-extra">
            <p>诚信评分：<el-rate v-model="user.avgScore" disabled show-score :max="10"></el-rate></p>
            <p>累计就诊：{{ user.visitNumber }} 次</p>
            <p>累计预约：{{ user.appointmentNumber }} 次</p>
          </div>
          <div class="user-actions">
            <el-button type="primary" @click="showEditDialog">编辑资料</el-button>
            <!-- <el-button @click="showPasswordDialog">修改密码</el-button> -->
          </div>
        </div>
      </div>
    </el-card>

    <!-- 基本信息卡片 -->
    <div class="card-container">
      <el-card class="info-card">
        <template #header>
          <div class="card-title">详细信息</div>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户名">{{ user.userName }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ user.userAge }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ user.userSex }}</el-descriptions-item>
          <el-descriptions-item label="手机">{{ user.userPhone }}</el-descriptions-item>
          <el-descriptions-item label="电子邮箱">{{ user.userEmail }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>


    <!-- 编辑资料对话框 -->
    <el-dialog title="编辑资料" v-model="showEditForm" width="40%">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.userSex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="editForm.userAge" :min="0" :max="120" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="手机" prop="userPhone">
          <el-input v-model="editForm.userPhone" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="editForm.userEmail" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditForm = false">取消</el-button>
        <el-button type="primary" @click="saveProfile">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="showPasswordForm" width="40%">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordForm = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserDetails, updateUserService } from '@/api/user.js'
import {
  User,
  Lock,
  Notebook,
  Calendar,
  FirstAidKit,
  Document,
  Setting,
  Bell
} from '@element-plus/icons-vue'

export default {
  name: 'Profile',
  components: {
    User,
    Lock,
    Notebook,
    Calendar,
    FirstAidKit,
    Document,
    Setting,
    Bell
  },
  setup() {
    const loading = ref(true)
    const user = ref({
      userId: '',
      userName: '',
      userSex: '',
      userAge: 0,
      userPhone: '',
      userEmail: '',
      avgScore: 0,
      visitNumber: 0,
      appointmentNumber: 0
    })
    const showEditForm = ref(false)
    const editForm = ref({})
    const showPasswordForm = ref(false)
    const passwordForm = ref({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    const passwordFormRef = ref(null)

    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.value.newPassword) {
              callback(new Error('两次输入密码不一致!'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    const showEditDialog = () => {
      editForm.value = {
        ...user.value
      }
      showEditForm.value = true
    }

    const showPasswordDialog = () => {
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      showPasswordForm.value = true
    }

    // 获取用户信息
    const saveProfile = async () => {
      try {
        const res = await updateUserService(editForm.value)
        if (res.code === 200) {
          ElMessage.success('修改成功')
          showEditForm.value = false
        }
      } catch (error) {
        ElMessage.error('保存失败: ' + (error.message || '未知错误'))
      } finally {
        fetchUserDetails()
        loading.value = false
      }
    }

    const changePassword = async () => {
      try {
        await passwordFormRef.value.validate()
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const res = await updateUserService({
          userId: userInfo.userId,
          password: passwordForm.value.newPassword
        })
        if (res.code === 200) {
          ElMessage.success('密码修改成功，请重新登录')
          passwordForm.value = {
            oldPassword: '',
            newPassword: '', 
            confirmPassword: ''
          }
          showPasswordForm.value = false
        } else {
          ElMessage.warning(res.message || '密码修改失败')
        }
      } catch (error) {
        ElMessage.error('密码修改失败: ' + (error.message || '请检查输入是否正确'))
      }
    }

    const fetchUserDetails = async () => {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const res = await getUserDetails(userInfo.userId)

        if (res.code === 200) {
          user.value = {
            ...res.data,
            userId: userInfo.userId
          }

        }
      } catch (error) {
        ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
    onMounted(fetchUserDetails)

    return {
      loading,
      user,
      showEditForm,
      editForm,
      showPasswordForm,
      passwordForm,
      passwordRules,
      showEditDialog,
      showPasswordDialog,
      fetchUserDetails,
      saveProfile,
      changePassword
    }
  },
}
</script>

<style scoped>
.profile-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 28px;
  margin-bottom: 20px;
  color: #42b983;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.user-profile {
  margin-bottom: 30px;
}

.profile-header {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 30px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 24px;
  margin: 0 0 10px;
  color: #333;
}

.user-meta {
  margin-bottom: 15px;
}

.user-meta span {
  margin-right: 20px;
  color: #666;
}

.user-extra p {
  margin: 5px 0;
  color: #666;
}

.user-actions {
  margin-top: 20px;
}

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.info-card {
  height: 100%;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #42b983;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.action-item {
  text-align: center;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.action-icon {
  margin-bottom: 10px;
  color: #42b983;
}

.action-text {
  font-size: 14px;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
  }

  .user-avatar {
    margin-right: 0;
    margin-bottom: 20px;
  }

  .user-meta {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }

  .user-meta span {
    margin-right: 0;
  }

  .card-container {
    grid-template-columns: 1fr;
  }

  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
